<template>

  <div class="home">
    <div class="home-main">
      <el-row class="top_row">
        <el-col style="font-size:12px;padding-top:6px;padding-left:10px">
          <span class="msg-title">PDI信息输入</span>
        </el-col>
        <el-row class="top_rows">
          <el-col :span="3" style="font-size:12px">
            <div>
              <span>产品牌号</span>
              <el-input v-model="headerSearchForm.SteelGrade" placeholder="请输入"
                style="width:80px;height:20px;margin-left:4px;" />
            </div>
          </el-col>
          <el-col :span="3" style="font-size:12px;">
            <div>
              <span>屈服强度</span>
              <el-input v-model="headerSearchForm.YP" placeholder="请输入"
                style="width:80px;height:20px;margin-left:4px" />
              <span>MPa</span>
            </div>
          </el-col>
          <el-col :span="3" style="font-size:12px;">
            <div>
              <span>入口厚度</span>
              <el-input v-model="headerSearchForm.res_EN_THICK" placeholder="请输入"
                style="width:80px;height:20px;margin-left:4px" />
              <span>mm</span>
            </div>
          </el-col>
          <el-col :span="3" style="font-size:12px;">
            <div>
              <span>成品厚度</span>
              <el-input v-model="headerSearchForm.res_EX_THICK" placeholder="请输入"
                style="width:80px;height:20px;margin-left:4px" />
              <span>mm</span>
            </div>
          </el-col>
          <el-col :span="3" style="font-size:12px;">
            <div>
              <span>宽度</span>
              <el-input v-model="headerSearchForm.res_EX_WIDTH" placeholder="请输入"
                style="width:80px;height:20px;margin-left:4px" />
              <span>mm</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div style="display: flex; justify-content: flex-end; gap: 10px; width:100%;">
              <el-button type="primary" @click="searchButtonClick" style="height:20px;">查询工艺参数</el-button>
              <el-button type="success" @click="handleQuote" style="height:20px;">批量导入</el-button>
            </div>
          </el-col>
        </el-row>
        <el-row class="top_rows" style="margin-bottom:10px">
          <el-col :span="5" style="font-size:12px;">
            <div>
              <span>任务名称</span>
              <el-input v-model="headerSearchForm.CoilNo" placeholder="请输入"
                style="width:160px;height:20px;margin-left:4px" />
            </div>
          </el-col>
          <el-col :span="5" style="font-size:12px;margin-left:10px">
            <div>
              <span>提交人</span>
              <el-input v-model="headerSearchForm.submitter" placeholder="请输入"
                style="width:160px;height:20px;margin-left:4px" />
            </div>
          </el-col>
          <el-col :span="5" style="font-size:12px;">
            <div>
              <span>备注</span>
              <el-input v-model="headerSearchForm.remarks" placeholder="请输入"
                style="width:180px;height:20px;margin-left:4px" />
            </div>
          </el-col>


        </el-row>



      </el-row>

      <el-row class="top_row">
        <el-col style="font-size:12px;padding-top:10px;padding-left:10px">
          <span class="msg-title">轧制规程参数</span>
        </el-col>

        <div class="card-panel">
          <div class="card-panel-left">
            <el-table :data="topList" style="width: 100%;height:auto;margin-top:1px;"
              :header-cell-style="{ background: '#2f59af', color: '#fff', fontSize: '12px' }"
              :cell-style="{ fontSize: '12px' }">
              <el-table-column prop="TITLE" label="轧制规程参数" />
              <el-table-column label="S5机架">
                <template #default="scope">
                  <el-input v-model="scope.row.S5" size="small" placeholder="请输入" />
                </template>
              </el-table-column>
              <el-table-column label="S4机架">
                <template #default="scope">
                  <el-input v-model="scope.row.S4" size="small" placeholder="请输入" />
                </template>
              </el-table-column>
              <el-table-column label="S3机架">
                <template #default="scope">
                  <el-input v-model="scope.row.S3" size="small" placeholder="请输入" />
                </template>
              </el-table-column>
              <el-table-column label="S2机架">
                <template #default="scope">
                  <el-input v-model="scope.row.S2" size="small" placeholder="请输入" />
                </template>
              </el-table-column>
              <el-table-column label="S1机架">
                <template #default="scope">
                  <el-input v-model="scope.row.S1" size="small" placeholder="请输入" />
                </template>
              </el-table-column>
              <el-table-column prop="BEFORE" label="机架前">
                <template #default="scope">
                  <el-input v-model="scope.row.BEFORE" size="small" placeholder="请输入" />
                </template>
              </el-table-column>
            </el-table>
            <div class="card-panel-form-left">
              <span style="font-size:12px;">L</span>
              <el-input v-model="headerSearchForm.productionLine_L" placeholder="请输入" style="width:80px;height:20px;" />
              <span style="font-size:12px;">M</span>
              <el-input v-model="headerSearchForm.productionLine_M" placeholder="请输入" style="width:80px;height:20px;" />
              <span style="font-size:12px;">N</span>
              <el-input v-model="headerSearchForm.productionLine_N" placeholder="请输入" style="width:80px;height:20px;" />
            </div>
          </div>
          <div class="card-panel-middle-curve">
            <nercar-echarts :graphic="echartsListOptions2[0].graphic" :title="echartsListOptions2[0].title"
              :grid="echartsListOptions2[0].grid" :x-axis="echartsListOptions2[0].xAxis"
              :y-axis="echartsListOptions2[0].yAxis" :tooltip="echartsListOptions2[0].tooltip"
              :series="echartsListOptions2[0].series" style="width:260px;height:190px !important;margin-bottom:16px;" />
          </div>
          <div class="card-panel-right">
            <nercar-echarts :graphic="echartsListOptions[0].graphic" :title="echartsListOptions[0].title"
              :grid="echartsListOptions[0].grid" :x-axis="echartsListOptions[0].xAxis"
              :y-axis="echartsListOptions[0].yAxis" :tooltip="echartsListOptions[0].tooltip"
              :series="echartsListOptions[0].series" style="width:260px;height:190px !important;margin-bottom:16px;" />
            <div class="card-panel-form-row">

              <div class="card-panel-form-right">
                <el-button type="primary" @click="handleQuote" style="height:20px;">设备极限能力</el-button>
                <el-button type="success" @click="handleSimulationCalculate" style="height:20px;">仿真计算</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-row>

      <el-row class="top_row">
        <el-col style="font-size:12px;padding-top:15px;padding-left:10px">
          <span class="msg-title">仿真计算结果输出</span>
        </el-col>


        <el-row class="top_rows">
          <el-col style="font-size:12px;">
            <el-table :data="footTable" style="width: 98%"
              :header-cell-style="{ background: '#2f59af', color: '#fff', fontSize: '12px' }"
              :cell-style="{ fontSize: '12px' }">
              <el-table-column prop="卷号" label="计算结果" width="180" />
              <el-table-column prop="STD5" label="S5机架" />
              <el-table-column prop="STD4" label="S4机架" />
              <el-table-column prop="STD3" label="S3机架" />
              <el-table-column prop="STD2" label="S2机架" />
              <el-table-column prop="STD1" label="S1机架" />
              <el-table-column prop="BEFORE" label="机架前" />

            </el-table>
          </el-col>
        </el-row>

      </el-row>



    </div>
  </div>

  <el-dialog v-model="importDialogVisible" title="批量导入" width="500px" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <div class="import-dialog-content">
      <div class="template-section">
        <div class="section-title">模板下载</div>
        <div class="template-actions">
          <el-button type="primary" @click="downloadTemplate" size="small">
            下载模板
          </el-button>
        </div>
      </div>
      <div class="upload-section">
        <div class="section-title">文件上传</div>
        <el-upload class="upload-demo" drag :before-upload="beforeUpload" :show-file-list="false" :auto-upload="false"
          :on-change="(uploadFile: import('element-plus').UploadFile) => { if (uploadFile.raw) { handleFileChange(uploadFile.raw); } }"
          accept=".xlsx,.xls">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传 Excel 文件（.xlsx, .xls）
            </div>
          </template>
        </el-upload>
        <div v-if="showUploadPreview">
          <div style="margin: 10px 0; font-weight: bold;">预览</div>
          <el-table :data="uploadPreviewData" style="width: 100%" size="small">
            <el-table-column v-for="(col, index) in uploadPreviewColumns" :key="index" :prop="col.prop"
              :label="col.label" width="120">
            </el-table-column>
          </el-table>
          <el-button type="primary" style="margin-top: 10px;" @click="handleUploadConfirm">确认导入</el-button>
        </div>
      </div>
    </div>
  </el-dialog>

</template>

<script setup lang='ts'>
import { rollingSimulationApi } from '/@/api/RollingSimulation/index'
import { reactive, ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'

interface SearchForm {
  SteelGrade: string;  // 钢牌号
  YP: string;          // 屈服强度
  res_EN_THICK: string; // 入口厚度
  res_EX_THICK: string; // 出口厚度
  res_EX_WIDTH: string; // 出口宽度
  CoilNo: string;       // 卷号或者叫任务名称
  productionLine: string; // 保留原始字段，如果其他地方仍在使用
  productionLine_L?: string; // LMN作为可选新字段
  productionLine_M?: string;
  productionLine_N?: string;
  submitter?: string; // 新增提交人
  remarks?: string;   // 新增备注
}
const headerSearchForm = reactive<SearchForm>({
  SteelGrade: 'DC01',
  YP: '240',
  res_EN_THICK: '4.00',
  res_EX_THICK: '1.18',
  res_EX_WIDTH: '1625',
  CoilNo: 'X1234567890',
  productionLine: '',
  productionLine_L: '46',
  productionLine_M: '0.01',
  productionLine_N: '0.33',
  submitter: '默认提交人', // 添加默认值
  remarks: '默认备注',     // 添加默认值
});
interface TopListItem {
  TITLE: string;
  BEFORE: string;
  [key: string]: string; // 支持动态索引访问
}

const ARRAYLIST: TopListItem[] = [
  { TITLE: '工作辊直径(mm)', BEFORE: '-', S5: '-', S4: '-', S3: '-', S2: '-', S1: '-' },
  { TITLE: '比变形率', BEFORE: '-', S5: '-', S4: '-', S3: '-', S2: '-', S1: '-' },
  { TITLE: '轧制卷数', BEFORE: '-', S5: '-', S4: '-', S3: '-', S2: '-', S1: '-' },
  { TITLE: '单位张力(MPa)', BEFORE: '-', S5: '-', S4: '-', S3: '-', S2: '-', S1: '-' }
];
const topList = reactive<TopListItem[]>([...ARRAYLIST]);
const defaultFootTable = [
  { '卷号': '出口厚度(mm)', 'BEFORE': '-', 'STD1': '-', 'STD2': '-', 'STD3': '-', 'STD4': '-', 'STD5': '-' },
  { '卷号': '最终压下率(%)', 'BEFORE': '-', 'STD1': '-', 'STD2': '-', 'STD3': '-', 'STD4': '-', 'STD5': '-' },
  { '卷号': '机架速度(mpm)', 'BEFORE': '-', 'STD1': '-', 'STD2': '-', 'STD3': '-', 'STD4': '-', 'STD5': '-' },
  { '卷号': '张力(kN)', 'BEFORE': '-', 'STD1': '-', 'STD2': '-', 'STD3': '-', 'STD4': '-', 'STD5': '-' },
  { '卷号': '轧制力(kN)', 'BEFORE': '-', 'STD1': '-', 'STD2': '-', 'STD3': '-', 'STD4': '-', 'STD5': '-' },
  { '卷号': '辊缝(mm)', 'BEFORE': '-', 'STD1': '-', 'STD2': '-', 'STD3': '-', 'STD4': '-', 'STD5': '-' },
  { '卷号': '前滑值(%)', 'BEFORE': '-', 'STD1': '-', 'STD2': '-', 'STD3': '-', 'STD4': '-', 'STD5': '-' },
  { '卷号': '电机功率(kW)', 'BEFORE': '-', 'STD1': '-', 'STD2': '-', 'STD3': '-', 'STD4': '-', 'STD5': '-' },
];
const footTable = ref<Array<Record<string, any>>>([...defaultFootTable]);
const echartsListOptions = reactive([
  {
    title: {
      show: true,
      text: '变形抗力',
      textStyle: {
        color: 'black',
        fontSize: 12,
      }
    },

    graphic: [
      {
        type: 'text',
        bottom: 45, // 距离底部的固定距离
        right: 16, // 距离底部的固定距离
        style: {
          text: '(m)', // X轴名称
          fill: 'black',
          fontSize: 12,
          align: 'center'
        }
      }
    ],
    toolbox: {
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        },
        restore: {},
        saveAsImage: {}
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: { color: '#fff' },
        crossStyle: { color: '#6d7882' }
      }
    },
    grid: {
      left: '1%',
      right: '32%',
      bottom: '9%',
      containLabel: true
    },
    dataZoom: [
      {
        type: 'slider', //滑动条
        show: true, //开启
        xAxisIndex: [0]
      }, //X轴内置滑动
      {
        type: 'inside', //内置滑动，随鼠标滚轮展示
        xAxisIndex: [0]
      }
    ],
    xAxis: [
      {
        type: 'category',
        name: '变形率(%)',
        nameLocation: 'end',     //设置name位置  start或者end

        nameTextStyle: {

          color: "black",

          fontSize: 8,

          padding: [0, 0, 0, -10] // 四个数字分别为上右下左与原位置距离

        },
        data: ['A', 'B', 'C', 'D'],
        splitLine: { show: false },
        axisLabel: {
          textStyle: {
            color: 'black'
          }

        }

      }
    ],
    yAxis: {
      type: 'value',
      name: '屈服强度(MPa)',
      nameTextStyle: {
        fontSize: '8px',
        color: 'black' // 设置 y 轴名称的颜色为红色
      },
      scale: true, //纵坐标自适应
      splitLine: {
        show: false
      },
      axisLabel: {
        textStyle: {
          color: 'black'
        }

      }

    },
    series: [

      {
        name: '',
        data: [10, 22, 28, 43],
        type: 'line',
        stack: 'x',
        smooth: true,
        symbolSize: 1,
      }]
  }]);
const echartsListOptions2 = [
  {
    title: {
      show: true,
      text: '张力-变形抗力',
      textStyle: {
        color: 'black',
        fontSize: 12,
      }
    },

    graphic: [
      {
        type: 'text',
        bottom: 45, // 距离底部的固定距离
        right: 16, // 距离底部的固定距离
        style: {
          text: '', // X轴名称
          fill: 'black',
          fontSize: 12,
          align: 'center'
        }
      }
    ],
    toolbox: {
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        },
        restore: {},
        saveAsImage: {}
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: { color: '#fff' },
        crossStyle: { color: '#6d7882' }
      }
    },
    grid: {
      left: '6%',
      right: '29%',
      bottom: '9%',
      containLabel: true
    },
    dataZoom: [
      {
        type: 'slider', //滑动条
        show: true, //开启
        xAxisIndex: [0]
      }, //X轴内置滑动
      {
        type: 'inside', //内置滑动，随鼠标滚轮展示
        xAxisIndex: [0]
      }
    ],
    xAxis: [
      {
        type: 'category',
        name: '变形抗力',
        nameLocation: 'end',     //设置name位置  start或者end

        nameTextStyle: {

          color: "black",

          fontSize: 8,

          padding: [0, 0, 0, -10] // 四个数字分别为上右下左与原位置距离

        },
        data: ['0', '10', '20', '30', '40', '50'],
        splitLine: { show: false },
        axisLabel: {
          textStyle: {
            color: 'black'
          }

        }

      }
    ],
    yAxis: {
      type: 'value',
      name: '张力(kN)',
      nameTextStyle: {
        fontSize: '8px',
        color: 'black' // 设置 y 轴名称的颜色为红色
      },
      scale: true, //纵坐标自适应
      splitLine: {
        show: false
      },
      axisLabel: {
        textStyle: {
          color: 'black'
        }

      }

    },
    series: [

      {
        name: '',
        data: [10, 22, 28, 43],
        type: 'line',
        stack: 'x',
        smooth: true,
        symbolSize: 1,
      }]
  }];
function searchButtonClick() {
  let param = {
    "action": "send_msg",
    "body": {
      "msgId": 2026,
      "params": [
        [
          { ...headerSearchForm }
        ]
      ],
      "sendTo": "TCM_SIM",
      "timeout": 5,
      "waitReply": true
    },
    "operator": "director",
    "terminal": "director"
  }
  rollingSimulationApi.HMI(param).then(res => {
    const obj = res.data.results[0][0];

    const editableRowTitles = ['工作辊直径(mm)', '比变形率', '轧制卷数'];
    const editableDataFieldKeys = ['Diameter', 'Deform_Rate', 'Roll_Num'];
    const newTopList: TopListItem[] = [];

    editableRowTitles.forEach((title, index) => {
      const row: TopListItem = {
        TITLE: title,
        BEFORE: '-',
      };
      const fieldPrefix = editableDataFieldKeys[index];
      for (let i = 1; i <= 5; i++) { // For S1, S2, S3, S4, S5 keys
        const val = obj[fieldPrefix + i];
        if (title === '工作辊直径(mm)') {
          // 工作辊直径取整
          row['S' + i] = val === 0 ? '0' : (val ? String(Math.round(Number(val))) : '');
        } else {
          row['S' + i] = val === 0 ? '0' : (val || '');
        }
      }
      newTopList.push(row);
    });

    const unitTensionRowData: TopListItem = {
      TITLE: '单位张力(MPa)',
      BEFORE: obj.Unit_Tension1 === 0 ? 0 : (obj.Unit_Tension1 || '-'),
      S5: obj.Unit_Tension6 === 0 ? 0 : (obj.Unit_Tension6 || '-'),
      S4: obj.Unit_Tension5 === 0 ? 0 : (obj.Unit_Tension5 || '-'),
      S3: obj.Unit_Tension4 === 0 ? 0 : (obj.Unit_Tension4 || '-'),
      S2: obj.Unit_Tension3 === 0 ? 0 : (obj.Unit_Tension3 || '-'),
      S1: obj.Unit_Tension2 === 0 ? 0 : (obj.Unit_Tension2 || '-'),
    };
    newTopList.push(unitTensionRowData);

    topList.splice(0, topList.length, ...newTopList);

    // Update footTable for consistency
    const footTableUnitTensionRow = footTable.value.find(row => row.卷号 === '单位张力(MPa)');
    if (footTableUnitTensionRow) {
      footTableUnitTensionRow.钢种 = obj.Unit_Tension6 === 0 ? 0 : (obj.Unit_Tension6 || '-');
    }

    // 新增：同步L、M、N到输入框
    headerSearchForm.productionLine_L = obj.L ?? obj.l ?? '-';
    headerSearchForm.productionLine_M = obj.M ?? obj.m ?? '-';
    headerSearchForm.productionLine_N = obj.N ?? obj.n ?? '-';
  })
};

// 添加新的响应式变量
const importDialogVisible = ref(false)
const uploadedFile = ref<File | null>(null)
const uploadPreviewData = ref<any[]>([])
const uploadPreviewColumns = ref<any[]>([])
const showUploadPreview = ref(false)

// Helper function to safely convert values to numbers
function getNumericValue(value: any, defaultValue: number | null = null): number | null {
  if (value === null || value === undefined || String(value).trim() === '') {
    return defaultValue;
  }
  const num = Number(value);
  return isNaN(num) ? defaultValue : num;
}

// Helper function to format numbers to three decimal places for display
function formatNumberToThreeDecimals(value: any): string | number {
  if (value === '-' || value === null || value === undefined || String(value).trim() === '') {
    return value; // Return non-numeric placeholders or empty strings as is
  }
  const num = Number(value);
  if (isNaN(num)) {
    return value; // Return original value if it's not a number (e.g., an error message string)
  }
  return num.toFixed(3);
}

// 修改原有的handleQuote函数
async function handleQuote() {
  importDialogVisible.value = true
}

// 只保留下载模板方法
async function downloadTemplate() {
  // 直接调用api，内部已处理下载
  rollingSimulationApi.exportTemplate({});
}

// 上传前验证
function beforeUpload(file: File) {
  const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase())
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('文件大小不能超过 2MB!')
    return false
  }
  uploadedFile.value = file
  return true
}


// 解析Excel文件并预览
function handleFileChange(file: File) {
  uploadedFile.value = file;
  const reader = new FileReader();
  reader.onload = (e: any) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: 'array' });
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];
    const jsonData: any[][] = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); // Explicitly type jsonData
    const previewRows = jsonData.slice(0, 10);

    const headerSource = previewRows[0];
    uploadPreviewColumns.value = Array.isArray(headerSource)
      ? headerSource.map((col: any, idx: number) => ({
        prop: 'col' + idx,
        label: col != null ? String(col) : `列${idx + 1}`,
      }))
      : [];

    uploadPreviewData.value = previewRows.slice(1).map((dataRow: unknown) => {
      const obj: { [key: string]: string } = {};
      if (Array.isArray(dataRow)) {
        uploadPreviewColumns.value.forEach((columnDefinition: { prop: string; label: string }, columnIndex: number) => {
          const cellValue = dataRow[columnIndex];
          obj[columnDefinition.prop] = cellValue != null ? String(cellValue) : '';
        });
      }
      return obj;
    });
    showUploadPreview.value = true;
  };
  reader.readAsArrayBuffer(file);
}

// setup 顶部
const router = useRouter();

async function handleUploadConfirm() {
  if (!uploadedFile.value) {
    ElMessage.error('请先上传文件')
    return
  }
  const formData = new FormData()
  formData.append('file', uploadedFile.value)
  try {
    const res = await rollingSimulationApi.importData(formData)
    if (res.data && res.data.status === 2000) {
      ElMessage.success(res.data?.msg || '导入成功')
      showUploadPreview.value = false
      importDialogVisible.value = false
      // 跳转
      router.push({ path: '/rollingsimulation/case' });
    } else {
      ElMessage.error(res.data?.msg || '导入失败')
    }
  } catch (error) {
    ElMessage.error('导入失败')
  }
}

const route = useRoute();

onMounted(async () => {
  try {
    const taskName = route.query.taskName as string;
    if (taskName) {
      const response = await rollingSimulationApi.findCase({ volumeNum: taskName });
      // 兼容不同API返回结构
      const caseData = response.data?.data || response.data || {};
      console.log('caseData:', caseData);
      // PDI信息
      headerSearchForm.SteelGrade = caseData.steelGrade || '-';
      headerSearchForm.YP = caseData.yp || '-';
      headerSearchForm.res_EN_THICK = caseData.enThick || '-';
      headerSearchForm.res_EX_THICK = caseData.exThick || '-';
      headerSearchForm.res_EX_WIDTH = caseData.exWidth || '-';
      headerSearchForm.CoilNo = caseData.coilNo || '-';
      headerSearchForm.submitter = caseData.operator || '-';
      headerSearchForm.remarks = caseData.remark || '-';
      // 兼容 findCase 返回小写字段
      headerSearchForm.productionLine_L = caseData.l ?? caseData.L ?? '-';
      headerSearchForm.productionLine_M = caseData.m ?? caseData.M ?? '-';
      headerSearchForm.productionLine_N = caseData.n ?? caseData.N ?? '-';
      // 轧制规程参数
      const topListData = [
        {
          TITLE: '工作辊直径(mm)',
          S5: caseData.wrDia5 !== undefined ? String(Math.round(caseData.wrDia5)) : '-',
          S4: caseData.wrDia4 !== undefined ? String(Math.round(caseData.wrDia4)) : '-',
          S3: caseData.wrDia3 !== undefined ? String(Math.round(caseData.wrDia3)) : '-',
          S2: caseData.wrDia2 !== undefined ? String(Math.round(caseData.wrDia2)) : '-',
          S1: caseData.wrDia1 !== undefined ? String(Math.round(caseData.wrDia1)) : '-',
          BEFORE: '-'
        },
        {
          TITLE: '比变形率',
          S5: caseData.deformRate5 ?? '-',
          S4: caseData.deformRate4 ?? '-',
          S3: caseData.deformRate3 ?? '-',
          S2: caseData.deformRate2 ?? '-',
          S1: caseData.deformRate1 ?? '-',
          BEFORE: '-'
        },
        {
          TITLE: '轧制卷数',
          S5: caseData.nr5 ?? '-',
          S4: caseData.nr4 ?? '-',
          S3: caseData.nr3 ?? '-',
          S2: caseData.nr2 ?? '-',
          S1: caseData.nr1 ?? '-',
          BEFORE: '-'
        },
        {
          TITLE: '单位张力(MPa)',
          BEFORE: caseData.unitTension1 ?? caseData.Unit_Tension1 ?? '-',
          S5: caseData.unitTension6 ?? caseData.Unit_Tension6 ?? '-',
          S4: caseData.unitTension5 ?? caseData.Unit_Tension5 ?? '-',
          S3: caseData.unitTension4 ?? caseData.Unit_Tension4 ?? '-',
          S2: caseData.unitTension3 ?? caseData.Unit_Tension3 ?? '-',
          S1: caseData.unitTension2 ?? caseData.Unit_Tension2 ?? '-'
        }
      ];
      topList.splice(0, topList.length, ...topListData);
      const footTableData = [
        {
          '卷号': '出口厚度(mm)',
          STD5: caseData.thk5 !== undefined ? Number(caseData.thk5).toFixed(3) : '-',
          STD4: caseData.thk4 !== undefined ? Number(caseData.thk4).toFixed(3) : '-',
          STD3: caseData.thk3 !== undefined ? Number(caseData.thk3).toFixed(3) : '-',
          STD2: caseData.thk2 !== undefined ? Number(caseData.thk2).toFixed(3) : '-',
          STD1: caseData.thk1 !== undefined ? Number(caseData.thk1).toFixed(3) : '-',
          BEFORE: '-'
        },
        {
          '卷号': '机架速度(mpm)',
          STD5: caseData.speed5 ?? '-',
          STD4: caseData.speed4 ?? '-',
          STD3: caseData.speed3 ?? '-',
          STD2: caseData.speed2 ?? '-',
          STD1: caseData.speed1 ?? '-',
          BEFORE: '-'
        },
        {
          '卷号': '张力(kN)',
          STD5: caseData.tension5 !== undefined ? (caseData.tension5 * 10).toFixed(3) : '-',
          STD4: caseData.tension4 !== undefined ? (caseData.tension4 * 10).toFixed(3) : '-',
          STD3: caseData.tension3 !== undefined ? (caseData.tension3 * 10).toFixed(3) : '-',
          STD2: caseData.tension2 !== undefined ? (caseData.tension2 * 10).toFixed(3) : '-',
          STD1: caseData.tension1 !== undefined ? (caseData.tension1 * 10).toFixed(3) : '-',
          BEFORE: caseData.tension6 !== undefined ? (caseData.tension6 * 10).toFixed(3) : '-'
        },
        {
          '卷号': '轧制力(kN)',
          STD5: caseData.rollForce5 !== undefined ? (caseData.rollForce5 * 10).toFixed(3) : '-',
          STD4: caseData.rollForce4 !== undefined ? (caseData.rollForce4 * 10).toFixed(3) : '-',
          STD3: caseData.rollForce3 !== undefined ? (caseData.rollForce3 * 10).toFixed(3) : '-',
          STD2: caseData.rollForce2 !== undefined ? (caseData.rollForce2 * 10).toFixed(3) : '-',
          STD1: caseData.rollForce1 !== undefined ? (caseData.rollForce1 * 10).toFixed(3) : '-',
          BEFORE: '-'
        },
        {
          '卷号': '电机转矩(kN)',
          STD5: caseData.motorMoment5 !== undefined ? (caseData.motorMoment5 * 10).toFixed(3) : '-',
          STD4: caseData.motorMoment4 !== undefined ? (caseData.motorMoment4 * 10).toFixed(3) : '-',
          STD3: caseData.motorMoment3 !== undefined ? (caseData.motorMoment3 * 10).toFixed(3) : '-',
          STD2: caseData.motorMoment2 !== undefined ? (caseData.motorMoment2 * 10).toFixed(3) : '-',
          STD1: caseData.motorMoment1 !== undefined ? (caseData.motorMoment1 * 10).toFixed(3) : '-',
          BEFORE: '-'
        },
        {
          '卷号': '电机功率(kW)',
          STD5: caseData.power5 ?? '-',
          STD4: caseData.power4 ?? '-',
          STD3: caseData.power3 ?? '-',
          STD2: caseData.power2 ?? '-',
          STD1: caseData.power1 ?? '-',
          BEFORE: '-'
        },
        {
          '卷号': '辊缝(mm)',
          STD5: caseData.gap5 !== undefined ? Number(caseData.gap5).toFixed(3) : '-',
          STD4: caseData.gap4 !== undefined ? Number(caseData.gap4).toFixed(3) : '-',
          STD3: caseData.gap3 !== undefined ? Number(caseData.gap3).toFixed(3) : '-',
          STD2: caseData.gap2 !== undefined ? Number(caseData.gap2).toFixed(3) : '-',
          STD1: caseData.gap1 !== undefined ? Number(caseData.gap1).toFixed(3) : '-',
          BEFORE: '-'
        },
        {
          '卷号': '前滑值(%)',
          STD5: caseData.forslip5 !== undefined ? (Number(caseData.forslip5) * 100).toFixed(2) + '%' : '-',
          STD4: caseData.forslip4 !== undefined ? (Number(caseData.forslip4) * 100).toFixed(2) + '%' : '-',
          STD3: caseData.forslip3 !== undefined ? (Number(caseData.forslip3) * 100).toFixed(2) + '%' : '-',
          STD2: caseData.forslip2 !== undefined ? (Number(caseData.forslip2) * 100).toFixed(2) + '%' : '-',
          STD1: caseData.forslip1 !== undefined ? (Number(caseData.forslip1) * 100).toFixed(2) + '%' : '-',
          BEFORE: '-'
        }
      ];
      console.log("footTableData", footTableData)
      footTable.value = footTableData;
      ElMessage.success('案例数据加载成功');
    } else {
      // 没有参数时自动查询工艺参数
      searchButtonClick();
    }
  } catch (error) {
    ElMessage.error('加载案例数据失败');
  }
});

async function handleSimulationCalculate() {
  console.log('仿真计算按钮点击');

  const apiParams: Record<string, any> = {};

  // PDI Info
  apiParams['CoilNo'] = headerSearchForm.CoilNo || '';
  apiParams['SteelGrade'] = headerSearchForm.SteelGrade || '';
  apiParams['YP'] = getNumericValue(headerSearchForm.YP);
  apiParams['res_EN_THICK'] = getNumericValue(headerSearchForm.res_EN_THICK);
  // Assuming res_EX_WIDTH from PDI form is for res_EN_WIDTH based on typical PDI fields
  apiParams['res_EN_WIDTH'] = getNumericValue(headerSearchForm.res_EX_WIDTH);
  apiParams['res_EX_THICK'] = getNumericValue(headerSearchForm.res_EX_THICK);
  apiParams['res_EX_WIDTH'] = getNumericValue(headerSearchForm.res_EX_WIDTH); // This is actual exit width

  // L, M, N values
  apiParams['L'] = getNumericValue(headerSearchForm.productionLine_L);
  apiParams['M'] = getNumericValue(headerSearchForm.productionLine_M);
  apiParams['N'] = getNumericValue(headerSearchForm.productionLine_N);

  // Parameters from topList
  const diameterRow = topList.find(r => r.TITLE === '工作辊直径(mm)');
  const deformRateRow = topList.find(r => r.TITLE === '比变形率');
  const rollNumRow = topList.find(r => r.TITLE === '轧制卷数');
  const unitTensionRow = topList.find(r => r.TITLE === '单位张力(MPa)');

  for (let i = 1; i <= 5; i++) {
    apiParams[`Diameter${i}`] = diameterRow ? getNumericValue(diameterRow[`S${i}`]) : null;
    apiParams[`Deform_Rate${i}`] = deformRateRow ? getNumericValue(deformRateRow[`S${i}`]) : null;
    apiParams[`Roll_Num${i}`] = rollNumRow ? getNumericValue(rollNumRow[`S${i}`]) : null;
  }

  if (unitTensionRow) {
    apiParams['Unit_Tension1'] = getNumericValue(unitTensionRow.BEFORE);
    apiParams['Unit_Tension2'] = getNumericValue(unitTensionRow.S1);
    apiParams['Unit_Tension3'] = getNumericValue(unitTensionRow.S2);
    apiParams['Unit_Tension4'] = getNumericValue(unitTensionRow.S3);
    apiParams['Unit_Tension5'] = getNumericValue(unitTensionRow.S4);
    apiParams['Unit_Tension6'] = getNumericValue(unitTensionRow.S5);
  }

  // myuXX values
  Object.assign(apiParams, {
    myu10: 0.026, myu11: 3.5, myu12: 100, myu13: 0, myu14: 1.1, myu15: 0.002,
    myu20: 0.022, myu21: 4.8, myu22: 80, myu23: 0, myu24: 1.2, myu25: 0.004,
    myu30: 0.02, myu31: 4.8, myu32: 80, myu33: 0, myu34: 1.2, myu35: 0.004,
    myu40: 0.02, myu41: 4.8, myu42: 80, myu43: 0, myu44: 1.1, myu45: 0.002,
    myu50: 0.15, myu51: 5.0, myu52: 150, myu53: 0, myu54: 1.0, myu55: 0
  });

  const finalApiParams: Record<string, any> = {};
  for (const key in apiParams) {
    if (apiParams[key] !== null && apiParams[key] !== undefined) { // Ensure nulls/undefined are not sent if not desired
      finalApiParams[key] = apiParams[key];
    }
  }

  const requestPayload = {
    action: "send_msg",
    body: {
      msgId: 2028,
      params: [[finalApiParams]],
      sendTo: "TCM_SIM",
      timeout: 10,
      waitReply: true
    },
    operator: "director",
    terminal: "director"
  };

  console.log("Sending to API:", JSON.stringify(requestPayload, null, 2));

  try {
    const res = await rollingSimulationApi.HMI(requestPayload);
    console.log("API Response:", res);

    if (res && res.data && res.data.results && res.data.results[0] && res.data.results[0][0]) {
      const resultData = res.data.results[0][0];
      const newFootTableData = [];

      const formatRow = (label: string, prefix: string, sixValues: boolean, unit: string = '', valueHandler?: (v: any) => any) => {
        const row: Record<string, any> = { '卷号': `${label}${unit ? ' (' + unit + ')' : ''}` };
        const keys = sixValues
          ? [1, 2, 3, 4, 5, 6]
          : [1, 2, 3, 4, 5];
        const beforeVal = resultData[`${prefix}${keys[0]}`];

        // 格式化规则
        const intLabels = ['张力', '机架速度', '轧制力', '电机转矩', '电机功率', '工作辊直径'];
        function formatValue(label: string, value: any) {
          if (value === '-' || value === null || value === undefined || value === '') return value;
          if (intLabels.some(l => label.includes(l))) {
            return Math.round(Number(value));
          }
          return value;
        }

        row['BEFORE'] = formatValue(label, valueHandler ? valueHandler(beforeVal) : beforeVal);

        if (!sixValues) {
          row['BEFORE'] = '-';
          for (let i = 0; i < 5; i++) {
            const val = resultData[`${prefix}${keys[i]}`];
            row[`STD${i + 1}`] = formatValue(label, valueHandler ? valueHandler(val) : val);
          }
        } else {
          for (let i = 0; i < 5; i++) {
            const val = resultData[`${prefix}${keys[i + 1]}`];
            row[`STD${i + 1}`] = formatValue(label, valueHandler ? valueHandler(val) : val);
          }
        }
        return row;
      };

      newFootTableData.push(formatRow('出口厚度', 'EXITTHK', false, 'mm', v => v !== undefined && v !== null && v !== '-' ? Number(v).toFixed(3) : v));
      newFootTableData.push(formatRow('机架速度', 'SPEED', true, 'mpm'));
      newFootTableData.push(formatRow('张力', 'TENSION', true, 'kN', v => v * 10));
      newFootTableData.push(formatRow('轧制力', 'ROLLFORCE', false, 'kN', v => v * 10));
      newFootTableData.push(formatRow('电机转矩', 'MOTORMOMENT', false, 'kN', v => v * 10));
      newFootTableData.push(formatRow('辊缝', 'GAP', false, 'mm', v => v !== undefined && v !== null && v !== '-' ? Number(v).toFixed(3) : v));
      newFootTableData.push(formatRow('前滑值', 'FORSLIP', false, '%', v => v !== undefined && v !== null && v !== '-' ? (Number(v) * 100).toFixed(2) + '%' : v));
      newFootTableData.push(formatRow('电机功率', 'MOTORPOWER', false, 'kW'));
      // 新增：最终压下率(%)
      newFootTableData.push({
        '卷号': '最终压下率(%)',
        BEFORE: '-',
        STD1: resultData.Reds_final1 !== undefined && resultData.Reds_final1 !== null ? (Number(resultData.Reds_final1) / 100).toFixed(2) + '%' : '-',
        STD2: resultData.Reds_final2 !== undefined && resultData.Reds_final2 !== null ? (Number(resultData.Reds_final2) / 100).toFixed(2) + '%' : '-',
        STD3: resultData.Reds_final3 !== undefined && resultData.Reds_final3 !== null ? (Number(resultData.Reds_final3) / 100).toFixed(2) + '%' : '-',
        STD4: resultData.Reds_final4 !== undefined && resultData.Reds_final4 !== null ? (Number(resultData.Reds_final4) / 100).toFixed(2) + '%' : '-',
        STD5: resultData.Reds_final5 !== undefined && resultData.Reds_final5 !== null ? (Number(resultData.Reds_final5) / 100).toFixed(2) + '%' : '-',
      });

      footTable.value = newFootTableData;
      console.log("仿真", footTable)
      // --- Call updateCase API --- 
      const updateCasePayload: Record<string, any> = {};

      updateCasePayload['coilNo'] = headerSearchForm.CoilNo || '';
      updateCasePayload['steelGrade'] = headerSearchForm.SteelGrade || '';
      updateCasePayload['yp'] = getNumericValue(headerSearchForm.YP);
      updateCasePayload['enThick'] = getNumericValue(headerSearchForm.res_EN_THICK);
      updateCasePayload['exThick'] = getNumericValue(headerSearchForm.res_EX_THICK);
      updateCasePayload['enWidth'] = getNumericValue(headerSearchForm.res_EX_WIDTH);
      updateCasePayload['exWidth'] = getNumericValue(headerSearchForm.res_EX_WIDTH);
      updateCasePayload['operator'] = headerSearchForm.submitter || '';
      updateCasePayload['remark'] = headerSearchForm.remarks || '';

      updateCasePayload['l'] = getNumericValue(headerSearchForm.productionLine_L);
      updateCasePayload['m'] = getNumericValue(headerSearchForm.productionLine_M);
      updateCasePayload['n'] = getNumericValue(headerSearchForm.productionLine_N);
      // 删除大写L/M/N
      delete updateCasePayload['L'];
      delete updateCasePayload['M'];
      delete updateCasePayload['N'];
      // 新增rfNewV和ksv
      updateCasePayload['rfNewV'] = resultData.RF_NEW_V || null;
      updateCasePayload['ksv'] = resultData.KS_V || null;

      const diameterRowForUpdate = topList.find(r => r.TITLE === '工作辊直径(mm)');
      const rollNumRowForUpdate = topList.find(r => r.TITLE === '轧制卷数');
      const deformRateRowForUpdate = topList.find(r => r.TITLE === '比变形率');
      const unitTensionRowForUpdate = topList.find(r => r.TITLE === '单位张力(MPa)');

      for (let i = 1; i <= 5; i++) {
        updateCasePayload[`wrDia${i}`] = diameterRowForUpdate ? getNumericValue(diameterRowForUpdate[`S${i}`]) : null;
        updateCasePayload[`nr${i}`] = rollNumRowForUpdate ? getNumericValue(rollNumRowForUpdate[`S${i}`]) : null;
        updateCasePayload[`deformRate${i}`] = deformRateRowForUpdate ? getNumericValue(deformRateRowForUpdate[`S${i}`]) : null;
      }

      if (unitTensionRowForUpdate) {
        updateCasePayload['unitTension6'] = getNumericValue(unitTensionRowForUpdate.BEFORE);
        for (let i = 1; i <= 5; i++) {
          updateCasePayload[`unitTension${i}`] = getNumericValue(unitTensionRowForUpdate[`S${i}`]);
        }
      }

      for (let i = 1; i <= 6; i++) {
        const tensionVal = resultData[`TENSION${i}`];
        updateCasePayload[`tension${i}`] = tensionVal === 0 ? 0 : (tensionVal || null);
      }

      // Add power, rollForce, rollingForceSet, thk, speed (all 1-5) from resultData
      for (let i = 1; i <= 5; i++) {
        updateCasePayload[`thk${i}`] = getNumericValue(resultData[`EXITTHK${i}`]);
        updateCasePayload[`speed${i}`] = getNumericValue(resultData[`SPEED${i}`]);
        updateCasePayload[`rollForce${i}`] = getNumericValue(resultData[`ROLLFORCE${i}`]);
        updateCasePayload[`power${i}`] = getNumericValue(resultData[`MOTORPOWER${i}`]);
        updateCasePayload[`gap${i}`] = getNumericValue(resultData[`GAP${i}`]);
        updateCasePayload[`forslip${i}`] = getNumericValue(resultData[`FORSLIP${i}`]);

        const rfsValue = resultData[`ROLLINGFORECESET${i}`] !== undefined
          ? resultData[`ROLLINGFORECESET${i}`]
          : resultData[`ROLLINGFORCESET${i}`];
        updateCasePayload[`rollingForceSet${i}`] = getNumericValue(rfsValue);
      }

      const finalUpdateCasePayload: Record<string, any> = {};
      for (const key in updateCasePayload) {
        if (updateCasePayload[key] !== null && updateCasePayload[key] !== undefined) {
          finalUpdateCasePayload[key] = updateCasePayload[key];
        }
      }

      try {
        console.log("Calling rollingSimulationApi.updateCase with payload:", JSON.stringify(finalUpdateCasePayload, null, 2));
        // Assuming rollingSimulationApi.updateCase takes the payload object directly
        const updateRes = await rollingSimulationApi.updateCase(finalUpdateCasePayload);
        console.log("rollingSimulationApi.updateCase Response:", updateRes);
        // You might want to add a success message to the user here via ElMessage or similar
      } catch (updateError) {
        console.error("rollingSimulationApi.updateCase call failed:", updateError);
        // You might want to add an error message to the user here
      }
      // --- End of updateCase API call ---

      // 新增：渲染变形抗力曲线图（KS_V为纵坐标，RF_NEW_V为横坐标）
      if (resultData.KS_V && resultData.RF_NEW_V) {
        const ksArr = String(resultData.KS_V).split(',').map(v => v.trim()).filter(v => v !== '').map(Number);
        let rfArr = String(resultData.RF_NEW_V).split(',').map(v => v.trim()).filter(v => v !== '').map(Number);
        // 横坐标等距平均分布并乘以100
        if (rfArr.length > 1) {
          const min = Math.min(...rfArr);
          const max = Math.max(...rfArr);
          const step = (max - min) / (rfArr.length - 1);
          rfArr = Array.from({ length: rfArr.length }, (_, i) => ((min + i * step) * 100));
        } else if (rfArr.length === 1) {
          rfArr = [rfArr[0] * 100];
        }
        // 转为字符串数组
        const rfArrStr = rfArr.map(v => v.toFixed(2));
        if (Array.isArray(ksArr) && Array.isArray(rfArrStr) && ksArr.length === rfArrStr.length && ksArr.length > 0) {
          echartsListOptions[0].series[0].data = ksArr;
          echartsListOptions[0].xAxis[0].data = rfArrStr;
        }
      }

    } else {
      console.error("Unexpected API response structure:", res);
      footTable.value = [{ '卷号': '错误', 'BEFORE': '未能获取有效数据', 'STD1': '-', 'STD2': '-', 'STD3': '-', 'STD4': '-', 'STD5': '-' }];
    }
  } catch (error) {
    console.error("API call failed:", error);
    footTable.value = [{ '卷号': '错误', 'BEFORE': 'API调用失败', 'STD1': '-', 'STD2': '-', 'STD3': '-', 'STD4': '-', 'STD5': '-' }];
  }
}

</script>

<style scoped lang="less">
.home {
  min-height: 100vh;
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  background-image: linear-gradient(to top, #eaf1fb 0%, #2c69e8 100%) !important;
  padding: 16px;
  box-sizing: border-box;
  overflow: hidden;
}

.home-main {
  flex: 1 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  max-width: 100vw;
  width: 100vw;
  min-width: 0;
  margin: 0;
  padding: 0 8px 8px 8px;
  box-sizing: border-box;
}

.top_row,
.top_rows {
  border-radius: 0;
  border: none;
  width: 100%;
  background: transparent;
  padding: 4px 0 0 0;
  margin: 0;
  box-shadow: none;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  gap: 8px;
}

.top_row>.el-col,
.top_rows>.el-col {
  padding: 0 !important;
  margin: 0 !important;
}

.msg-title {
  font-size: 1em;
  font-weight: bold;
  color: #2056b3;
  margin-bottom: 4px;
  text-align: left;
  padding-left: 0;
}

.el-input,
.el-input__inner {
  font-size: 12px !important;
  height: 24px !important;
  min-height: 24px !important;
  padding: 0 4px !important;
}

.el-button {
  font-size: 12px !important;
  height: 24px !important;
  min-height: 24px !important;
  padding: 0 10px !important;
}

.card-panel {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  width: 100%;
  max-width: 100vw;
  border-radius: 0;
  padding: 0;
  margin: 0 0 4px 0;
  gap: 12px;
  background: transparent;
  box-shadow: none;
}

.card-panel-left {
  flex: 2 1 0;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.card-panel-right {
  flex: 1 1 0;
  min-width: 180px;
  max-width: 260px;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: flex-start;
  gap: 8px;
}

.card-panel-form-left,
.card-panel-form-right {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 4px;
}

.el-table {
  font-size: 12px !important;
  --el-table-header-bg-color: #eaf1fb;
  --el-table-header-text-color: #2056b3;
  --el-table-row-hover-bg-color: #f0f6ff;
}

.el-table th,
.el-table td {
  padding: 2px 4px !important;
  height: 24px !important;
}

.tabTable,
.card-panel-form-row {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-end;
  margin-top: 2px;
  gap: 6px;
}

.import-dialog-content {
  .section-title {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 8px;
    color: #2056b3;
  }

  .template-section {
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #EBEEF5;

    .template-actions {
      text-align: right;
    }
  }

  .upload-section {
    .el-upload {
      width: 100%;
    }

    .el-upload-dragger {
      width: 100%;
      height: 120px;
    }

    .el-upload__tip {
      color: #909399;
      font-size: 12px;
      margin-top: 4px;
    }
  }
}

@media (max-width: 1200px) {
  .card-panel {
    flex-direction: column;
    gap: 8px;
  }

  .card-panel-right {
    max-width: 100vw;
    width: 100%;
    align-items: flex-start;
  }
}

@media (max-width: 900px) {
  .home-main {
    padding: 0 2px 2px 2px;
  }

  .card-panel {
    flex-direction: column;
    gap: 4px;
  }

  .card-panel-left,
  .card-panel-right {
    width: 100%;
    min-width: 0;
    max-width: 100vw;
  }
}

@media (max-width: 600px) {
  .msg-title {
    font-size: 0.95em;
  }

  .el-input,
  .el-input__inner,
  .el-button {
    font-size: 11px !important;
    height: 20px !important;
    min-height: 20px !important;
  }

  .el-table th,
  .el-table td {
    font-size: 11px !important;
    height: 20px !important;
    padding: 1px 2px !important;
  }
}

html,
body,
.home,
.home-main {
  overflow: hidden !important;
}

// 10. 恢复"单位张力(MPa)"行输入框的正常显示和输入功能，不做任何隐藏或特殊样式处理。
.card-panel-left .el-table tbody tr {

  &[data-row-title="单位张力(MPa)"] .el-input,
  &[data-row-title="单位张力(MPa)"] .el-input__wrapper {
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
  }

  &[data-row-title="单位张力(MPa)"] .el-input__inner {
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
    color: #333 !important;
    min-width: 40px;
    min-height: 20px;
    height: 24px;
    outline: none !important;
  }
}

// 11. 按钮区域优化和美化
.card-panel-form-row {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-end;
  margin-top: 12px;
  gap: 16px;
  padding-right: 12px;
}

.el-button {
  font-size: 14px !important;
  height: 36px !important;
  min-width: 110px;
  border-radius: 20px !important;
  box-shadow: 0 2px 8px rgba(44, 105, 232, 0.08);
  color: #fff;
  border: none;
  transition: box-shadow 0.2s, background 0.2s, transform 0.1s;
  cursor: pointer;
}

.el-button:hover {
  box-shadow: 0 4px 16px rgba(44, 105, 232, 0.18);
  transform: scale(1.04);
}

.el-button:active {
  box-shadow: 0 1px 4px rgba(44, 105, 232, 0.18);
  transform: scale(0.98);
}

.el-button[type="success"] {
  background-image: linear-gradient(90deg, #34d97b 0%, #1abc9c 100%);
  color: #fff;
}

.el-button[type="success"]:hover {
  background-image: linear-gradient(90deg, #1abc9c 0%, #34d97b 100%);
  box-shadow: 0 4px 16px rgba(52, 217, 123, 0.18);
  transform: scale(1.04);
}

.el-button[type="success"]:active {
  box-shadow: 0 1px 4px rgba(52, 217, 123, 0.18);
  transform: scale(0.98);
}

// 12. 按钮在小屏下自适应
@media (max-width: 900px) {
  .card-panel-form-row {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
    padding-right: 0;
  }

  .el-button {
    min-width: 90px;
    width: 100%;
  }
}

// 13. 轧制规程参数表格所有输入框可输入但隐藏边框和背景，内容可见
:deep(.card-panel-left .el-table .el-input__wrapper) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

:deep(.card-panel-left .el-table .el-input__inner) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
  color: #333 !important;
  min-width: 40px;
  min-height: 20px;
  height: 24px;
  outline: none !important;
  padding: 0 2px !important;
}

:deep(.card-panel-left .el-table .el-input__inner:focus) {
  background: #fff !important;
  color: #2056b3 !important;
}

// 14. 强制"批量导入"与"仿真计算"按钮为绿色
.el-button[type='success'],
.el-button.success {
  background-image: linear-gradient(90deg, #34d97b 0%, #1abc9c 100%) !important;
  color: #fff !important;
  border: none !important;
}

.el-button[type='success']:hover,
.el-button.success:hover {
  background-image: linear-gradient(90deg, #1abc9c 0%, #34d97b 100%) !important;
}

.card-panel-middle-curve {
  flex: 1 1 0;
  min-width: 180px;
  max-width: 260px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  gap: 8px;
}
</style>